package com.tms.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tms.admin.entity.TmsAdmin;
import com.tms.admin.entity.vo.LoginVO;
import com.tms.admin.handler.TMSException;
import com.tms.admin.service.TmsAdminService;
import com.tms.admin.mapper.TmsAdminMapper;
import com.tms.common.entity.ResultCode;
import com.tms.common.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
* @author uni1024
* @description 针对表【tms_admin】的数据库操作Service实现
* @createDate 2022-09-06 19:54:11
*/
@Service
public class TmsAdminServiceImpl extends ServiceImpl<TmsAdminMapper, TmsAdmin>
    implements TmsAdminService{

    @Autowired
    HttpServletRequest httpServletRequest;
    @Override
    public String login(LoginVO loginVO) {
        /**
         * Step 1. 根据 VO 获取到 管理员的名称和密码
         * Step 2. 根据用户名和密码 查询 管理员
         * Step 3. 若管理员为空, 则抛出异常
         * Step 4. 根据管理员的ID和密码生成token , 并返回
         */
        // Step 1
        String username = loginVO.getUsername();
        String password = loginVO.getPassword();
        // Step 2
        LambdaQueryWrapper<TmsAdmin> wrapper =new LambdaQueryWrapper<>();
        wrapper.eq(TmsAdmin::getUsername, username);
        wrapper.eq(TmsAdmin::getPassword, password);
        TmsAdmin admin = baseMapper.selectOne(wrapper);
        // Step 3
        if(admin == null)
            throw new TMSException(ResultCode.FAIL, "用户名或密码错误");
        // Step 4
        String token = JwtUtil.getJwtToken(admin.getId(), admin.getPassword());
        return token;
    }

    @Override
    public void logout(String token) {
        HttpSession session = httpServletRequest.getSession();
        session.invalidate();
    }

    @Override
    public TmsAdmin getByToken(String token) {
        // Step1 调用JutUtils 从token中取得用户id
        String id = JwtUtil.getUserIdByJwtToken(token);
        // Step2 通过id获取用户信息
        if ("".equals(id)){
            throw new TMSException(ResultCode.TOKEN,"token无效");
        }
        TmsAdmin user = baseMapper.selectById(id);
        if (user == null){
            throw new TMSException(ResultCode.TOKEN,"token无效");
        }
        return user;
    }
}




